clc;
clear;
global num_firm T_sim S T n_theta beta n_tran tau mktfe search T_cal country_num rho_par country_num phi



%% solve + simulation
num_firm = 11000; %11575
T_sim = 240; % simulated periods, need to drop first a few
T_cal = 96; %week result
S = 10; % number of realizations
T = 25; % after T periods, it's full learning
n_theta = 100; % # of possible firm draws
%sigma = 2500; % mark up
beta = 0.999;
rho_par = 2.41;
n_tran = 100; % discretize firm state for each firm
input = csvread('~\online-mkt-fe.csv',1,1);
mktfe = input(3,2);
tau = input(3,3);
countrycode = input(:,4);
learngrowth = [];
wc_vec = [];
for k = 1:30
    search = 1;
    phi = input(k,4);
    country_num = size(search,1);
    rand('seed',0);
    replace_sim = rand(num_firm,T_sim,S);
    rand('seed',1);
    country_sim = rand(num_firm,T_sim,S);
    country_search = nan(size(country_sim));
    rand('seed',2);
    exit_sim = rand(num_firm,T_sim,S);
    rand('seed',3);
    purchase_sim = rand(num_firm,T_sim,S);
    rand('seed',4);
    ads_sim = rand(num_firm,T_sim,S);
    rand('seed',5);
    feedback_sim = rand(num_firm,T_sim,S);
     for j = 1:S
           country_search(:,:,j) = transform(repmat(search,1,num_firm),country_sim(:,:,j)'); 
     end;
    SIM = struct('sim_matrix_num',6);
    SIM.replace = replace_sim;
    SIM.country = country_search;
    SIM.exit = exit_sim;
    SIM.purchase = purchase_sim;
    SIM.ads = ads_sim;
    SIM.feedback = feedback_sim;

    x = [ -8.7699     -0.96234      0.59034       1.9198];
    ave_theta = exp(x(1));
    h_eps =   exp(x(2)); % positive and bigger than h_theta
    if h_eps>0.3988
        h_theta =   exp(x(3))+ exp(x(2)); % positive,0.3987
    else
        h_theta = 0.3988 + exp(x(3));
    end
    wc = -2.41*h_theta./phi-1; %1*104 1/variance for each country, ave_theta>max(-phi/2.41) =0.4078 to ensure positive wc
    delta = 0.02;
    cost = exp(x(4)); % positive
    gamma = 0;
step = 1;
learn = 2;
[mom_ave2] = simulate(ave_theta, h_theta, h_eps, delta, cost,gamma,wc, SIM,step,learn); 
learn = 1;
[mom_ave1] = simulate(ave_theta, h_theta, h_eps, delta, cost,gamma,wc, SIM,step,learn);
learngrowth = [learngrowth;mom_ave1./mom_ave2-1]
wc_vec = [wc_vec;wc];
end
countrycode = ['RUS';
'BRA';
'USA';
'ESP';
'FRA';
'CAN';
'CHL';
'ISR';
'GBR';
'AUS';
'UKR';
'CZE';
'EST';
'LVA';
'KAZ';
'SWE';
'BEL';
'ITA';
'CHE';
'NZL';
'NLD';
'COL';
'LTU';
'MEX';
'POL';
'LBN';
'TUR';
'BGR';
'DEU';
'SGP']
scatter(1./wc_vec, learngrowth)
xlabel('Market Information Friction \sigma_u^2') 
ylabel('Effect of Learning Regime')
dx = 0.0001; dy = 0.0001; % displacement so the text does not overlay the data points
%text(1./wc_vec+dx, learngrowth+dy, countrycode,'FontSize',5);


